package com.zhangxu.microservice.employee.web.response;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class PageResponse<T> implements Serializable {

    @Schema(description = "当前页")
    private Integer currentPage;
    @Schema(description = "每页大小")
    private Integer pageSize;
    @Schema(description = "总页数")
    private Integer totalPage;
    @Schema(description = "总行数")
    private Integer totalRow;
    @Schema(description = "数据列表")
    private List<T> items;


    public static <S, T> PageResponse<T> convert(IPage<S> source, Function<S, T> dataMapper) {
        if (null == source || null == dataMapper) {
            return null;
        }
        PageResponse<T> result = new PageResponse<>();
        result.setCurrentPage((int) source.getCurrent());
        result.setPageSize((int) source.getSize());
        result.setTotalPage((int) source.getPages());
        result.setTotalRow((int) source.getTotal());
        if (null != source.getRecords()) {
            result.setItems(source.getRecords().stream().map(dataMapper).collect(Collectors.toList()));
        }
        return result;
    }

}
